package com.nytd.demo.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final long EXPIRATION = 7 * 24 * 60 * 60 * 1000; // 7天
    private static final String SECRET_KEY = "ddhdsuhjbjkcuhshcxhvnvchfdiydsuudvvvcbvncvmmcv";

    // 生成密钥 - 注意：secretKey需要是Base64编码的
    private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

    public static String genJwt(Map<String, Object> claim) {

        String token = Jwts.builder()
                .setClaims(claim)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY, SignatureAlgorithm.HS256) // 明确指定算法
                .compact();

        return token;

    }

    public static Boolean parseJwt(String token) {
        if (!StringUtils.hasLength(token)) {
            return false;
        }
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
